package cn.yh.springsecurity.service.impl;

import cn.yh.springsecurity.domain.entity.LoginUser;
import cn.yh.springsecurity.domain.entity.User;
import cn.yh.springsecurity.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;




    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.eq(User::getUserName, username);

        User user = userMapper.selectOne(lqw);
        if (user == null){
            throw new RuntimeException("当前"+username+"用户不存在");
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);


        List<String> userPerms = userMapper.selectUserPerms(user.getUserId());
        loginUser.setPermissions(userPerms);

        return loginUser;
    }
}
